package com.abysshal.icarte.datamodel;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class Config {
		public static int SERVER_LISTEN_PORT = 10020;
		
		public static int VERBOSE = 1;
		
		public static int MENU_VERSION = 1;
		
		/*parsedByArgs is used for check if parseConfig(args) has already 
		 *configured all vars. And configLength is the number of vars to 
		 *be configured.
		 **/
	
		private static int configLength = 3;
		
		private static String defaultConfigFilePath = ".\\config" + Config.MENU_VERSION;
		
		//receive no more than three args, only assign the first args.length vars
		public static void parseConfig(String args[]){
			try{
				int cnt = 0;
				char varLabel = ' ';
				while (cnt < args.length){
					if (cnt % 2 == 0){
						varLabel = args[cnt].charAt(1);
					}//label
					else{
						switch(varLabel){
						case 's':
							Config.SERVER_LISTEN_PORT = Integer.parseInt(args[cnt]);
							break;
						case 'v':
							Config.VERBOSE = Integer.parseInt(args[cnt]);
							break;
						case 'm':
							Config.MENU_VERSION = Integer.parseInt(args[cnt]);
							break;
						default:
						}
					}
					cnt++;
				}
			}catch (NumberFormatException e){
				e.printStackTrace();
			}
		}
		
		//receive no more than three args from file, only assign the first several args
		public static void parseConfig(File file){
			try {
				BufferedReader br = new BufferedReader(new FileReader(file));
				String line;
				int cnt = 0;
				try {
					while ((line = br.readLine()) != null && cnt < configLength){
						switch(cnt) {
						case 0:
							Config.SERVER_LISTEN_PORT = Integer.parseInt(line);
							break;
						case 1:
							Config.VERBOSE = Integer.parseInt(line);
							break;
						case 2:
							Config.MENU_VERSION = Integer.parseInt(line);
						}
						cnt++;
					}
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
				br.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		public static void saveConfig(){
			try {
				BufferedWriter bw = new BufferedWriter(new FileWriter(Config.defaultConfigFilePath));
				bw.write(Config.SERVER_LISTEN_PORT + "\n");
				bw.write(Config.VERBOSE + "\n");
				bw.write(Config.MENU_VERSION + "\n");
				bw.flush();
				bw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		public static void printArgs(){
			System.out.println(Config.SERVER_LISTEN_PORT + " " + Config.VERBOSE + " " + Config.MENU_VERSION + "\n");
		}
}

